<template>
	<view>
		<st-navigation title="合同管理" backgroundColor="#fff"></st-navigation>
		<view class="tabbar-wrapper">
			<view class="tabbar">
				<view v-for="(item, index) of tabs" :key="index" class="tab" :class="{ active: activeTab === index }"
					@click="handleClickTab(index)">
					<text>{{ item.label }}</text>
				</view>
			</view>
		</view>

		<scroll-view scroll-y="true" style="height: 80vh;">
			<view class="tabbar-content">
				<!-- 量房定金 -->
				<view class="lfdj" v-if="activeTab === 0">
					<view class="list">
						<view class="list-item">
							<view class="list-item_top">
								<view class="label">量房定金{{ userData.price }}元</view>
								<!-- <view class="btn">申请退款</view> -->
							</view>
							<view class="list-item_footer">
								<view class="time">预约日期: {{ userData.bookingtime }}</view>
								<view class="state">{{ lfdjStatus }}</view>
							</view>
						</view>
					</view>
				</view>
				<view class="sjht" v-if="activeTab === 1">
					<image :src="designerContract.contract_img" mode="widthFix" style="width: 100%"
						@click="previewImage(designerContract.contract_img)"></image>
					<view class="row" v-if="designerContract.order_status != 7">
						<view class="label"><text>*</text>身份证复印件 <text>(必传)</text></view>
						<view class="material flex align-center justify-between">
							<view class="upload-items">
								<view class="upload-item">
									<uni-file-picker limit="1" @select="handleSelectPicker($event, 'front')">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">正面</view>
								</view>
								<view class="upload-item">
									<uni-file-picker limit="1" @select="handleSelectPicker($event, 'back')">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">反面</view>
								</view>
								<!-- <view class="upload-item" v-if="idCardImage.signature">
									<uni-file-picker :value="idCardImageSignature" limit="1" :readonly="true">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">签名</view>
								</view> -->
							</view>

							<view class="signature">
								<button class="btn" type="primary" size="mini" v-if="buildContract.order_status === 2 && designerContract._signState">生效中</button>
								<button class="btn" type="primary" size="mini" v-else @click="handleDesignerSignature">签名</button>
							</view>

						</view>
					</view>
					<view class="actions">
						<button type="primary" v-if="designerContract.order_status === 0 || designerContract.order_status === 1"
							class="btn" @click="handleToPayDesigner">{{ designerContract.contract_price }}元待支付</button>

						<button type="primary" v-if="designerContract.order_status === 2 && designerContract._signState" class="btn"
							@click="handleToDowloadContract">下载设计合同</button>
					</view>

				</view>
				<view class="sght" v-if="activeTab === 2">
					<image :src="buildContract.contract_img" mode="widthFix" style="width: 100%"
						@click="previewImage(buildContract.contract_img)"></image>
					<view class="row" v-if="buildContract.order_status != 7">
						<view class="label"><text>*</text>身份证复印件 <text>(必传)</text></view>
						<view class="material flex align-center justify-between">
							<view class="upload-items">
								<view class="upload-item">
									<uni-file-picker limit="1" @select="handleSelectPicker($event, 'front')">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">正面</view>
								</view>
								<view class="upload-item">
									<uni-file-picker limit="1" @select="handleSelectPicker($event, 'back')">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">反面</view>
								</view>
								<!-- <view class="upload-item" v-if="idCardImage.signature">
									<uni-file-picker :value="idCardImageSignature" limit="1" :readonly="true">
										<view class="upload-btn">+</view>
									</uni-file-picker>
									<view class="upload-label">签名</view>
								</view> -->
							</view>

							<view class="signature">
								<button class="btn" type="primary" size="mini" v-if="buildContract.order_status === 2 && designerContract._signState">生效中</button>
								<button class="btn" type="primary" size="mini" v-else @click="handleBuildSignature">签名</button>
							</view>

						</view>
					</view>
					<view class="actions">
						<button type="primary" v-if="buildContract.order_status === 0 || buildContract.order_status === 1" class="btn"
							@click="handleToPayBuild">{{ buildContract.contract_price }}元待支付</button>

						<button type="primary" v-if="buildContract.order_status === 2 && designerContract._signState" class="btn"
							@click="handleToDowloadContract">下载施工合同</button>
					</view>
				</view>

				<view class="shfw" v-if="activeTab === 3">
					<view class="shfw-content">
						<view class="shfw-module">
							<view class="label">问题请求</view>
							<view class="content">
								<textarea placeholder="请填写您的问题..." v-model="afterSaleService.aftersales_ask"></textarea>
							</view>
						</view>
						<view class="shfw-module upload">
							<view class="label">上传照片</view>
							<view class="content">
								<uni-file-picker limit="9" @select="handleSelectAskPicker($event)"></uni-file-picker>
							</view>
						</view>

						<view class="actions">
							<button type="primary" class="btn" @click="handleBookingAsk">一键申请</button>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="signature-content" v-if="isShowSignature">
			<view class="signature-w">
				<l-signature disableScroll backgroundColor="#fff" ref="signatureRef"></l-signature>
			</view>
			<view class="signature-actions">
				<button type="primary" class="btn" @click="handleSignature">确定</button>
				<button type="default" class="btn" @click="handleClearSignature">清除</button>
			</view>

			<uni-icons class="close-btn" type="closeempty" size="30" @click="isShowSignature = false"></uni-icons>
		</view>

	</view>
</template>

<script>
export default {
	data() {
		return {
			id: '', // 客户详情id
			idCardImage: {
				front: '',
				back: '',
				signature: '',
			},

			isShowSignature: false,
			signatureType: '',


			activeTab: 0,
			userData: {},
			tabs: [{
				label: '量房定金',
			},
			{
				label: '设计合同',
			},
			{
				label: '施工合同',
			},
			{
				label: '售后服务',
			},
			],
			designerContract: {
				front: '',
				back: '',
				signature: '',
			},
			buildContract: {
				front: '',
				back: '',
				signature: '',
			},
			signOrder: {},

			// 售后服务
			afterSaleService: {
				id: '',
				aftersales_ask: '',
				aftersales_img: '',
			},


			payList: [],
			isbalance: false,
			loading: false,
			disabled: false,
		};
	},
	computed: {
		idCardImageSignature() {
			return [
				{
					"name": "签名",
					"extname": "png",
					"url": this.$wanlshop.ossYSM(this.idCardImage.signature, 100, 100),
				}
			]
		},
		lfdjStatus() {
			if ([2,3,4,5].indexOf(this.userData.order_status) > -1) {
				return '已支付';
			}
			if ([0, 1].indexOf(this.userData.order_status) > -1) {
				return '未支付';
			}
			if ([7].indexOf(this.userData.order_status) > -1) {
				return '已取消';
			}
			return ''
		}
	},
	async onLoad(option) {
		let { id } = option;
		if (!id) {
			uni.navigateBack({
				delta: 1
			});
			return;
		}

		this.id = id;
		await this.getUserData();

		/* let { userData } = option;
		if (!userData) {
			uni.navigateBack({
				delta: 1
			});
			return;
		}
		userData = JSON.parse(userData);
		this.userData = userData; */

		await this.getPayment();

		await this.queryContractDetail(1);
		await this.queryContractDetail(2);

		console.log(this.designerContract);
	},
	methods: {
		async getUserData() {
			await this.$api.get({
				url: '/wanlshop/booking/details',
				data: {
					id: this.id
				},
				success: res => {
					this.userData = res;
					this.userData.bookingtime = this.formatDate(this.userData.bookingtime * 1000);
					this.userData.createtime = this.formatDate(this.userData.createtime * 1000);
					this.userData.type = this.typeOptions.find(item => item.id == this.userData.type).name;

					this.userData['_userName'] = this.user['is_designer'] == 1 ? (this.userData['username'] || this.userData['nickname']) : (this.userData['designer_username'] || this.userData['designer_nickname']);
					this.userData['_userAvatar'] = this.user['is_designer'] == 1 ? this.userData['avatar'] : this.userData['designer_avatar'];
					this.userData['_userId'] = this.user['is_designer'] == 1 ? this.userData['user_id'] : this.userData['designer_id'];
				}
			})
		},
		formatDate(date) {
			let date1 = new Date(date);
			let year = date1.getFullYear();
			let month = date1.getMonth() + 1;
			let day = date1.getDate();
			return year + '.' + month + '.' + day;
		},
		async getPayment() {
			let method = 'wap';
			// #ifdef APP-PLUS
			method = 'app';
			// #endif
			// #ifdef MP-BAIDU
			method = 'mini';
			// #endif
			// #ifdef MP-WEIXIN
			method = 'miniapp';
			// #endif
			// #ifdef MP-ALIPAY
			method = 'mini';
			// #endif
			// #ifdef MP-QQ
			method = 'mini';
			// #endif
			this.payList = [{
				name: '余额支付',
				describe: '',
				type: 'balance',
				method: 'balance',
				state: this.isbalance ? true : false, // 是否可用
				select: this.isbalance ? true : false // 是否选中
			}];
			// #ifdef H5
			this.payList.push({
				name: '支付宝',
				describe: '',
				type: 'alipay',
				method: method,
				state: true,
				select: false
			}, {
				name: '微信支付',
				describe: '推荐使用微信支付',
				type: 'wechat',
				method: method,
				state: true,
				select: this.isbalance ? false : true
			});
			// #endif
			// #ifndef H5
			uni.getProvider({
				service: "payment",
				success: (e) => {
					e.provider.map((value) => {
						if (value == 'alipay') {
							this.payList.push({ name: '支付宝', describe: '', type: value, method: method, state: true, select: false });
						} else if (value == 'wxpay') {
							this.payList.push({ name: '微信支付', describe: '推荐使用微信支付', type: 'wechat', method: method, state: true, select: this.isbalance ? false : true });
						} else if (value == 'baidu') {
							this.payList.push({ name: '百度收银台', describe: '', type: value, method: method, state: true, select: false });
						} else if (value == 'appleiap') {
							this.payList.push({ name: 'Apple支付', describe: '', type: 'apple', method: method, state: true, select: false });
						}
					})
				}
			});
			// #endif
		},

		// 签订合同
		async handleSignatureToApi() {
			let params = {};
			if (this.activeTab == 1) {
				params = {
					contract_id: this.designerContract.contract_id,
					user_sign: this.designerContract.signature,
					id_card_front: this.designerContract.front,
					id_card_back: this.designerContract.back,
				}
			}
			if (this.activeTab == 2) {
				params = {
					contract_id: this.buildContract.contract_id,
					user_sign: this.buildContract.signature,
					id_card_front: this.buildContract.front,
					id_card_back: this.buildContract.back,
				}
			}

			await this.$api.post({
				url: '/wanlshop/contract/sign',
				data: params,
				success: res => {
					if (this.activeTab == 1) {
						this.designerContract = {
							...this.designerContract,
							...res,

							_signState: true,
						};
					}
					if (this.activeTab == 2) {
						this.buildContract = {
							...this.buildContract,
							...res,
							
							_signState: true,
						};
					}
				}
			});
		},

		handleDesignerSignature() {
			if (this.designerContract.order_status === 0 || this.designerContract.order_status === 1) {
				uni.showToast({
					title: '请先支付',
					icon: 'none',
				});
				return;
			}
			this.isShowSignature = true;
			// this.signatureType = 'designer'
		},
		// 支付设计合同
		async handleToPayDesigner() {
			uni.showLoading({
				title: '支付中',
				mask: true,
			});

			try {
				await this.$api.post({
					url: '/wanlshop/order/addSignOrder',
					data: {
						booking_id: this.userData['booking_id'],
						template_id: this.designerContract.template_id,
					},
					success: res => {
						this.designerContract = {
							...this.designerContract,
							...res,
						}

						let data = null;
						data = this.payList.find(x => x.type === 'wechat');
						data.method = 'miniapp';

						data.order_id = this.designerContract.order_id;

						// #ifdef MP
						uni.login({
							success: (e) => {
								this.wanlPay(data, e.code);
							},
							fail: (e) => {
								uni.showModal({
									content: "无法获取微信code,原因为: " + e.errMsg,
									showCancel: false
								})
								uni.hideLoading();
								this.loading = false;
								this.disabled = false;
							}
						})
						// #endif
						// #ifndef MP
						this.wanlPay(data);
						// #endif

					},
					error: err => {
						this.loading = false;
						this.disabled = false;
						uni.hideLoading();
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
				})
			} catch (error) {
				uni.hideLoading();
				console.log(error);
			}

		},

		async wanlPay(data, code = null) {
			await this.$api.post({
				url: '/wanlshop/pay/payment',
				data: {
					type: data.type,
					method: data.method,
					code: code,
					order_id: data.order_id
				},
				success: (res) => {
					if (data.type == 'wechat' && data.method == 'miniapp') {
						uni.requestPayment({
							appId: res.appId,
							nonceStr: res.nonceStr,
							package: res.package,
							paySign: res.paySign,
							signType: res.signType,
							timeStamp: res.timeStamp,
							success: (e) => {
								console.log(e, '小程序支付成功')
								this.paySuccess();
							},
							fail: (e) => {
								uni.showModal({
									content: "支付失败,原因为: " + e.errMsg,
									showCancel: false
								})
							},
							complete: () => {
								this.loading = false;
								this.disabled = false;
							}
						})
					}
				},
				error: (err) => {
					uni.showModal({
						content: err.msg,
						showCancel: false
					})
					this.loading = false;
					this.disabled = false;
					uni.hideLoading();

				}

			})
			this.loading = false;
			this.disabled = false;
			uni.hideLoading();

		},

		paySuccess() {
			uni.showModal({
				content: "支付成功",
				showCancel: false,
				success: () => {
				}
			})
			uni.hideLoading();
			// 刷新页面
			uni.redirectTo({
				url: `/pagesYSM/ysmMy/contract/contract?id=${this.id}`
			})

			/* if (this.activeTab === 1) {
				this.designerContract.order_status = 2;
			}
			if (this.activeTab === 2) {
				this.buildContract.order_status = 2;
			} */
		},

		handleBuildSignature() {
			if (this.buildContract.order_status === 0 || this.buildContract.order_status === 1) {
				uni.showToast({
					title: '请先支付',
					icon: 'none',
				});
				return;
			}
		},

		async handleToPayBuild() {
			uni.showLoading({
				title: '支付中',
				mask: true,
			});

			try {
				await this.$api.post({
					url: '/wanlshop/order/addSignOrder',
					data: {
						booking_id: this.userData['booking_id'],
						template_id: this.buildContract.template_id,
					},
					success: res => {
						this.buildContract = {
							...this.buildContract,
							...res,
						}

						let data = null;
						data = this.payList.find(x => x.type === 'wechat');
						data.method = 'miniapp';

						data.order_id = this.buildContract.order_id;

						// #ifdef MP
						uni.login({
							success: (e) => {
								this.wanlPay(data, e.code);
							},
							fail: (e) => {
								uni.showModal({
									content: "无法获取微信code,原因为: " + e.errMsg,
									showCancel: false
								})
								this.loading = false;
								this.disabled = false;
							}
						})
						// #endif
						// #ifndef MP
						this.wanlPay(data);
						// #endif

					},
					error: err => {
						this.loading = false;
						this.disabled = false;
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
					}
				})
			} catch (error) {
				console.log(error);
			}

			uni.hideLoading();
		},

		async queryContractDetail(type) {
			await this.$api.get({
				url: '/wanlshop/contract/detail',
				data: {
					type,
					// designer_id: this.userData['designer_id'],
					booking_id: this.userData['booking_id'],
				},
				success: res => {
					if (type === 1) {
						this.designerContract = {
							...this.designerContract,
							...res,
						};
					}
					if (type === 2) {
						this.buildContract = {
							...this.buildContract,
							...res
						};
					}
				}
			});
		},

		previewImage(image) {
			uni.previewImage({
				urls: [image],
			});
		},


		handleClickTab(index) {
			this.activeTab = index;
		},



		chooseImage() {
			uni.chooseImage({
				count: 1, // 默认9
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: res => {
					// 设置url的值，显示控件
					this.url = res.tempFilePaths[0];
				}
			});
			this.usermaks = this.$wanlshop.maks();
		},

		handleSelectPicker(e, type) {
			this.$api.upload({
				url: '/common/upload',
				filePath: e.tempFiles[0].path,
				name: 'file',
				success: res => {
					this.designerContract[type] = res.url;
				}
			});
		},


		handleSignature() {
			this.$refs.signatureRef.canvasToTempFilePath({
				success: (res) => {
					this.$api.upload({
						url: '/common/upload',
						filePath: res.tempFilePath,
						name: 'file',
						success: res => {
							// this.idCardImage.signature = res.url;
							this.isShowSignature = false;

							if (this.activeTab == 1) {
								this.designerContract.signature = res.url;

							}
							if (this.activeTab == 2) {
								this.buildContract.signature = res.url;
							}

							this.handleSignatureToApi();
						}
					});
				}
			})

		},
		handleClearSignature() {
			this.$refs.signatureRef['clear']()
		},


		handleToDowloadContract() {
			if (this.activeTab === 1) {
				this.previewImage(this.designerContract.contract_img);
			}
			if (this.activeTab === 2) {
				this.previewImage(this.buildContract.contract_img);
			}
		},


		handleSelectAskPicker(e) {
			this.$api.upload({
				url: '/common/upload',
				filePath: e.tempFiles[0].path,
				name: 'file',
				success: res => {
					this.afterSaleService.aftersales_img = res.url;
				}
			});
		},

		// https://www.ysmll.cn/api/wanlshop/booking/ask
		handleBookingAsk() {
			if (!this.afterSaleService.aftersales_ask) {
				uni.showToast({
					title: '请填写问题',
					icon: 'none'
				});
				return;
			}
			this.$api.post({
				url: '/wanlshop/booking/ask',
				data: {
					id: this.userData['id'],
					aftersales_ask: this.afterSaleService.aftersales_ask,
					aftersales_img: this.afterSaleService.aftersales_img,
				},
				success: res => {
					uni.showToast({
						title: '提交成功',
						icon: 'none'
					});
					this.afterSaleService = {
						aftersales_ask: '',
						aftersales_img: '',
					};
				}
			});

		},
	}
}
</script>

<style lang="less" scoped>
.tabbar-wrapper {
	background-color: #fff;
	padding: 22rpx 32rpx 32rpx;
}

.tabbar {
	// margin: 22rpx 32rpx 32rpx;
	display: flex;
	justify-content: space-around;
	align-items: center;
	border: 2rpx solid #4C7DD9;
	border-radius: 8rpx;
}

.tab {
	display: flex;
	flex: 1;
	flex-direction: column;
	align-items: center;
	font-size: 28rpx;
	line-height: 72rpx;
	padding: 0 24rpx;
	border-right: 2rpx solid #4C7DD9;
	font-weight: 400;


	color: #4C7DD9;

	&:last-child {
		border-right: none;
	}
}

.active {
	border: 1px solid #4C7DD9;
	background: #4C7DD9;
	color: #fff;
}

.tab img {
	width: 20px;
	height: 20px;
	margin-bottom: 5px;
}

/deep/ .tabbar-content {
	padding: 48rpx 32rpx;

}

.list-item {
	background: #fff;
	margin-bottom: 48rpx;
	border-radius: 4px;

	.list-item_top {
		display: flex;
		align-items: center;
		padding: 32rpx 0;
		font-weight: 600;
		font-size: 24rpx;
		line-height: 34rpx;
		border-bottom: 1px solid #E6E6E6;

		.label {
			padding: 0 26rpx 0 32rpx;
			// border-right: 2rpx solid #B3B3B3;
			color: #333333;
			margin-right: 32rpx;
		}

		.btn {
			color: #559C61;
		}
	}

	.list-item_footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 86rpx;
		line-height: 86rpx;
		font-weight: 400;
		font-size: 24rpx;

		.time {
			padding: 0 32rpx 0;

			color: #808080;
		}

		.state {
			padding: 0 64rpx;
			color: #fff;
			background: linear-gradient(90deg, #FE9F04 0%, #FE7E00 100%);
		}
	}

}

.sjht,
.sght {
	background-color: #fff;

	.row {
		padding: 36rpx;

		text {
			color: #F13130;
		}
	}
}

.upload-items {
	margin-top: 20rpx;
	display: flex;

	/deep/ .upload-item {
		width: 140rpx;

		.file-picker__box {
			width: 140rpx !important;
			height: 140rpx !important;
		}

		.upload-label {
			text-align: center;
			margin-top: 12rpx;
			color: #808080;

			font-weight: 400;
			font-size: 24rpx;
			line-height: 40rpx;
		}

		.signature-image {
			width: 114rpx !important;
			height: 114rpx !important;
		}
	}

	.upload-btn {
		font-size: 50rpx;
		color: #808080;
	}
}

.signature {
	.btn {
		background: #FE8101;
		border-radius: 200rpx;
	}
}

// 售后服务
.shfw-content {
	background: #fff;
	border: 1px solid #E6E6E6;
	border-radius: 8rpx;

	.shfw-module {
		border-bottom: 1px solid #E6E6E6;

		.label {
			padding: 32rpx;
			font-weight: 600;
			font-size: 28rpx;
			line-height: 40rpx;
			color: #333333;
			border-bottom: 1px solid #E6E6E6;
		}

		.content {
			padding: 32rpx;

			textarea {
				width: 100%;
				height: 280rpx;
				font-size: 28rpx;
				line-height: 34rpx;
				color: #333333;
			}
		}

		&.upload {
			min-height: 400rpx;

			.label {
				border-bottom: none;
				padding-bottom: 0;
			}

			.content {
				border-bottom: none;
			}
		}


	}



}

.actions {
	.btn {
		height: 96rpx;
		background: #FE8101;
	}
}

.signature-content {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9999;
	background: rgba(0, 0, 0, 0.5);
	padding: 40rpx;

	.signature-w {
		width: 100%;
		height: 80vh;
		background: #fff;
	}

	.signature-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;

		.btn {
			width: 200rpx;
			height: 80rpx;
			background: #FE8101;

			&:last-child {
				background: #fff;
				color: #FE8101;
			}

			&:first-child {
				color: #fff;
			}
		}
	}

	.close-btn {
		position: absolute;
		right: 60rpx;
		top: 60rpx;
	}
}
</style>